package com.uzai.console.service.wxqaddfriend.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.uzai.common.entity.User;
import com.uzai.common.enums.*;
import com.uzai.common.exception.BusinessException;
import com.uzai.common.msg.MsgDto;
import com.uzai.common.msg.NoticeMsgDto;
import com.uzai.common.result.ResponseCode;
import com.uzai.common.utils.EsIndexName;
import com.uzai.console.common.ResponseMsg;
import com.uzai.console.common.UzaiRespVo;
import com.uzai.console.common.utils.DateUtil;
import com.uzai.console.common.utils.Tools;
import com.uzai.console.constant.Const;
import com.uzai.console.constant.ES.ElasticsearchUtil;
import com.uzai.console.constant.ES.ElasticsearchUtilGroupMsg;
import com.uzai.console.dto.rocketmq.friendrequest.DeleteUserDto;
import com.uzai.console.dto.rocketmq.wechatuser.SetUserRemarkDto;
import com.uzai.console.dto.rocketmq.wxgroup.AddFriendReqDto;
import com.uzai.console.dto.rocketmq.wxgroup.AddFriendReqWxworkDto;
import com.uzai.console.dto.wxqaddfriend.wxqaddfriendtaskaddinfo.WxqAddFriendTaskAddInfoIdDto;
import com.uzai.console.dto.wxqaddfriend.wxqaddfriendtaskaddinfo.WxqAddFriendTaskAddInfoIdListDto;
import com.uzai.console.dto.wxqaddfriend.wxqaddfriendtaskaddinfo.WxqAddFriendTaskAddInfoQuery;
import com.uzai.console.dto.zombiefan.zombiefan.ZombieFanIdDto;
import com.uzai.console.dto.zombiefan.zombiefan.ZombieFanIdListDto;
import com.uzai.console.entity.*;
import com.uzai.console.entity.es.*;
import com.uzai.console.enums.WxqAddFriendTaskStatusEnum;
import com.uzai.console.enums.ZombieFanTaskStatusEnum;
import com.uzai.console.mapper.*;
import com.uzai.console.service.device.DeviceService;
import com.uzai.console.service.feign.UzaiImClientFeignService;
import com.uzai.console.service.merchant.MerchantService;
import com.uzai.console.service.rocketmq.NoticeMsgPushProducerService;
import com.uzai.console.service.user.UserService;
import com.uzai.console.service.wechatprivate.WxContactsService;
import com.uzai.console.service.wechatwork.WxworkContactsService;
import com.uzai.console.service.wxqaddfriend.WxqAddFriendTaskAddInfoService;
import com.uzai.console.vo.wxqaddfriend.wxqaddfriendtaskaddinfo.WxqAddFriendTaskAddInfoVo;
import lombok.Data;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 自动清理僵尸粉任务发送明细
 * @author liuqi
 * @date 2021年08月13日 11:34
 */
@Service
public class WxqAddFriendTaskAddInfoServiceImpl implements WxqAddFriendTaskAddInfoService {

    Logger logger = LoggerFactory.getLogger(WxqAddFriendTaskAddInfoServiceImpl.class);

    @Autowired
    private ZombieFanTaskMapper zombieFanTaskMapper;
    @Autowired
    private WxqAddFriendTaskAddInfoMapper wxqAddFriendTaskAddInfoMapper;
    @Autowired
    private DeviceService deviceService;
    @Autowired
    private WxqAddFriendTaskMapper wxqAddFriendTaskMapper;
    @Autowired
    private ElasticsearchUtil elasticsearchUtil;
    @Autowired
    private NoticeMsgPushProducerService noticeMsgPushProducerService;
    @Autowired
    private UzaiImClientFeignService uzaiImClientFeignService;
    @Autowired
    private MerchantService merchantService;
    @Autowired
    private ElasticsearchUtilGroupMsg elasticsearchUtilGroupMsg;

    /**
     * 查询清理僵尸粉任务列表
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param wxqAddFriendTaskAddInfoQuery
     * @return null
     */
    public Page<WxqAddFriendTaskAddInfoVo> findWxqAddFriendTaskAddInfoList(WxqAddFriendTaskAddInfoQuery wxqAddFriendTaskAddInfoQuery){

        Integer now = DateUtil.getNowTime();

        //新建返回到页面的LIST对象
        List<WxqAddFriendTaskAddInfoVo> wxqAddFriendTaskAddInfoVoList = new ArrayList<>();

        //执行分页查询对象
        Page<WxqAddFriendTaskAddInfo> page = new Page<>();
        wxqAddFriendTaskAddInfoQuery.convert(page);
        List<WxqAddFriendTaskAddInfo> wxqAddFriendTaskAddInfoList = wxqAddFriendTaskAddInfoMapper.findByList(page, wxqAddFriendTaskAddInfoQuery);
        if(wxqAddFriendTaskAddInfoList != null){
            for (WxqAddFriendTaskAddInfo wxqAddFriendTaskAddInfo : wxqAddFriendTaskAddInfoList){
                WxqAddFriendTaskAddInfoVo wxqAddFriendTaskAddInfoVo = new WxqAddFriendTaskAddInfoVo();
                BeanUtils.copyProperties(wxqAddFriendTaskAddInfo, wxqAddFriendTaskAddInfoVo);

                //查询群发类型名称
                if(org.apache.commons.lang3.StringUtils.isNotBlank(wxqAddFriendTaskAddInfo.getDeviceType())){
                    DeviceTypeEnum deviceTypeEnum = DeviceTypeEnum.getByKey(wxqAddFriendTaskAddInfo.getDeviceType());
                    if(deviceTypeEnum != null){
                        wxqAddFriendTaskAddInfoVo.setDeviceTypeName(deviceTypeEnum.getRemark());
                    }
                }

                //机器人信息
                if(wxqAddFriendTaskAddInfo.getDeviceUniqueId() != null){
                    Device device = deviceService.findDeviceInfoByDeviceUniqueId(wxqAddFriendTaskAddInfo.getDeviceUniqueId(), wxqAddFriendTaskAddInfo.getDeviceType(), wxqAddFriendTaskAddInfo.getMerId());
                    if(device != null){
                        wxqAddFriendTaskAddInfoVo.setDeviceId(device.getDeviceId());
                        wxqAddFriendTaskAddInfoVo.setDeviceName(device.getDeviceName());
                        wxqAddFriendTaskAddInfoVo.setDeviceRemark(device.getDeviceRemark());
                    }
                }

                wxqAddFriendTaskAddInfoVoList.add(wxqAddFriendTaskAddInfoVo);

            }
        }
        //返回到页面分页对象
        Page<WxqAddFriendTaskAddInfoVo> pageVo = new Page<>();
        BeanUtils.copyProperties(page, pageVo);
        pageVo.setRecords(wxqAddFriendTaskAddInfoVoList);
        //将分页信息复制到返回到页面的分页MO当中
        return pageVo;
    }

    /**
     * 查询添加好友任务明细详情
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param wxqAddFriendTaskAddInfoIdDto
     * @return null
     */
    public WxqAddFriendTaskAddInfoVo findWxqAddFriendTaskAddInfo(WxqAddFriendTaskAddInfoIdDto wxqAddFriendTaskAddInfoIdDto){
        //返回到页面的VO对象
        WxqAddFriendTaskAddInfoVo wxqAddFriendTaskAddInfoVo = new WxqAddFriendTaskAddInfoVo();

        if(wxqAddFriendTaskAddInfoIdDto.getId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAM_ERROR);
        }

        WxqAddFriendTaskAddInfo wxqAddFriendTaskAddInfo = wxqAddFriendTaskAddInfoMapper.selectById(wxqAddFriendTaskAddInfoIdDto.getId(), wxqAddFriendTaskAddInfoIdDto.getMerId());

        if(wxqAddFriendTaskAddInfo == null ){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该记录不存在");
        }

        //将查询到的数据复制到页面VO中
        BeanUtils.copyProperties(wxqAddFriendTaskAddInfo, wxqAddFriendTaskAddInfoVo);

        //查询群发类型名称
        if(org.apache.commons.lang3.StringUtils.isNotBlank(wxqAddFriendTaskAddInfo.getDeviceType())){
            DeviceTypeEnum deviceTypeEnum = DeviceTypeEnum.getByKey(wxqAddFriendTaskAddInfo.getDeviceType());
            if(deviceTypeEnum != null){
                wxqAddFriendTaskAddInfoVo.setDeviceTypeName(deviceTypeEnum.getRemark());
            }
        }

        //机器人信息
        if(wxqAddFriendTaskAddInfo.getDeviceUniqueId() != null){
            Device device = deviceService.findDeviceInfoByDeviceUniqueId(wxqAddFriendTaskAddInfo.getDeviceUniqueId(), wxqAddFriendTaskAddInfo.getDeviceType(), wxqAddFriendTaskAddInfo.getMerId());
            if(device != null){
                wxqAddFriendTaskAddInfoVo.setDeviceId(device.getDeviceId());
                wxqAddFriendTaskAddInfoVo.setDeviceName(device.getDeviceName());
                wxqAddFriendTaskAddInfoVo.setDeviceRemark(device.getDeviceRemark());
            }
        }

        return  wxqAddFriendTaskAddInfoVo;
    }

    /**
     * 批量处理清理僵尸粉任务
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param wxqAddFriendTaskAddInfoIdListDto
     * @return null
     */
    public void batchDeleteWxqAddFriendTaskAddInfo(WxqAddFriendTaskAddInfoIdListDto wxqAddFriendTaskAddInfoIdListDto){
        List<Long> idList = wxqAddFriendTaskAddInfoIdListDto.getIdList();
        if(idList == null || idList.size() == 0){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请选择记录");
        }

        if(wxqAddFriendTaskAddInfoIdListDto.getTaskId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请选择主任务id");
        }

        WxqAddFriendTask wxqAddFriendTask = wxqAddFriendTaskMapper.selectById(wxqAddFriendTaskAddInfoIdListDto.getTaskId(), wxqAddFriendTaskAddInfoIdListDto.getMerId());
        if(wxqAddFriendTask == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "主任务不存在");
        }

        for (Long id : idList) {
            //删除添加明细
            wxqAddFriendTaskAddInfoMapper.deleteById(id, wxqAddFriendTaskAddInfoIdListDto.getMerId());
        }

        //修改主任务的添加好友总数
        wxqAddFriendTask.setTotalNum(wxqAddFriendTask.getTotalNum() - idList.size());
        wxqAddFriendTask.setUpdateTime(DateUtil.getNowTime());
        wxqAddFriendTaskMapper.updateById(wxqAddFriendTask);
    }

    /**
     * 自动发送微信群内添加好友添加明细请求
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param wxqAddFriendTask
     * @return null
     */
    @Transactional
    public void autoSendWxqAddFriendTaskAddInfo(WxqAddFriendTask wxqAddFriendTask){
        if(wxqAddFriendTask == null){
            return;
        }

        //查询该机器人关联的最小id的发送明细
        WxqAddFriendTaskAddInfo wxqAddFriendTaskAddInfo = wxqAddFriendTaskAddInfoMapper.selectMinIdByDeviceUniqueId(wxqAddFriendTask.getDeviceUniqueId(), wxqAddFriendTask.getMerId());
        if(wxqAddFriendTaskAddInfo != null){ //发送好友请求中

            Device device = deviceService.findDeviceInfoByDeviceUniqueId(wxqAddFriendTaskAddInfo.getDeviceUniqueId(), wxqAddFriendTaskAddInfo.getDeviceType(), wxqAddFriendTaskAddInfo.getMerId());
            if(device == null){
                return;
            }

            //是否是黑名单
            Boolean blacklistFlag = false;

            if(wxqAddFriendTask.getDeviceType().equals(DeviceTypeEnum.DT_PC_WECHAT.getKey())){
                //是否私有黑名单过滤不添加
                if(Tools.getInteger(wxqAddFriendTask.getLimitBlacklistPri()) == 1){
                    //查询是否已经在黑名单当中
                    //id为merId_groupWxid_wxid
                    String blicklitPriId = wxqAddFriendTaskAddInfo.getMerId() + "_" + wxqAddFriendTaskAddInfo.getGroupWxid() + "_" + wxqAddFriendTaskAddInfo.getWxid();
                    Map<String,Object> map = elasticsearchUtil.searchDataById(EsIndexName.UZAI_WXQ_BLACKLIST_PRV, blicklitPriId, null);
                    WxqBlacklistPrv wxqBlacklistPrv  = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(map)), WxqBlacklistPrv.class);
                    if(wxqBlacklistPrv != null){
                        blacklistFlag = true;
                    }
                }

                //是否全网黑名单过滤不添加
                if(Tools.getInteger(wxqAddFriendTask.getLimitBlacklistPub()) == 1){
                    //查询是否已经在黑名单当中
                    //id为成员wxid
                    String blicklitPubId = wxqAddFriendTaskAddInfo.getWxid();
                    Map<String,Object> pub_map = elasticsearchUtil.searchDataById(EsIndexName.UZAI_WXQ_BLACKLIST_PUB, blicklitPubId, null);
                    WxqBlacklistPub wxqBlacklistPub  = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(pub_map)), WxqBlacklistPub.class);
                    if(wxqBlacklistPub != null){
                        blacklistFlag = true;
                    }
                }

                //不是黑名单，则发送添加好友
                if(!blacklistFlag){
                    //发送添加好友MQ消息
                    MsgDto<AddFriendReqDto> msgDto = new MsgDto<>();
                    AddFriendReqDto addFriendReqDto = new AddFriendReqDto();
                    addFriendReqDto.setWxid(wxqAddFriendTaskAddInfo.getWxid());
                    addFriendReqDto.setV2(wxqAddFriendTaskAddInfo.getGroupWxid()); //群wxid
                    addFriendReqDto.setVerifyMsg(Tools.getStr(wxqAddFriendTask.getVerifyMsg()));
                    msgDto.setContent(addFriendReqDto);
                    msgDto.setId(IdWorker.getId());
                    msgDto.setDeviceType(device.getRecvmsgType());
                    msgDto.setDeviceUniqueId(device.getId());
                    msgDto.setMerId(wxqAddFriendTaskAddInfo.getMerId());
                    msgDto.setMsgType(MessageFuncEnum.ADD_FRIEND_REQ.getValue());
                    noticeMsgPushProducerService.addFriendReq(msgDto);
                }

            }else if(wxqAddFriendTask.getDeviceType().equals(DeviceTypeEnum.DT_WORK_WECHAT.getKey())){
                //是否私有黑名单过滤不添加
                if(Tools.getInteger(wxqAddFriendTask.getLimitBlacklistPri()) == 1){
                    //查询是否已经在黑名单当中
                    //id为merId_groupWxid_wxid
                    String blicklitPriId = wxqAddFriendTaskAddInfo.getMerId() + "_" + wxqAddFriendTaskAddInfo.getGroupWxid() + "_" + wxqAddFriendTaskAddInfo.getWxid();
                    Map<String,Object> map = elasticsearchUtil.searchDataById(EsIndexName.UZAI_WXQ_WORK_BLACKLIST_PRV, blicklitPriId, null);
                    WxqWorkBlacklistPrv wxqWorkBlacklistPrv_old  = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(map)), WxqWorkBlacklistPrv.class);
                    if(wxqWorkBlacklistPrv_old != null){
                        blacklistFlag = true;
                    }
                }

                //是否全网黑名单过滤不添加
                if(Tools.getInteger(wxqAddFriendTask.getLimitBlacklistPub()) == 1){
                    //查询是否已经在黑名单当中
                    //id为成员wxid
                    String blicklitPubId = wxqAddFriendTaskAddInfo.getWxid();
                    Map<String,Object> pub_map = elasticsearchUtil.searchDataById(EsIndexName.UZAI_WXQ_WORK_BLACKLIST_PUB, blicklitPubId, null);
                    WxqWorkBlacklistPub wxqWorkBlacklistPub  = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(pub_map)), WxqWorkBlacklistPub.class);
                    if(wxqWorkBlacklistPub != null){
                        blacklistFlag = true;
                    }
                }

                //不是黑名单，则发送添加好友
                //企业微信发送走的微服务
                if(!blacklistFlag){

                    //查找该群成员的公司id
                    String corpid = "";
                    String memberId = wxqAddFriendTaskAddInfo.getMerId() + "_" + wxqAddFriendTaskAddInfo.getGroupWxid() +"_" + wxqAddFriendTaskAddInfo.getWxid();
                    String uzai_workwx_group_member = merchantService.getMechantOtherEsIndexName(EsIndexName.UZAI_WORKWX_GROUP_MEMBER, wxqAddFriendTaskAddInfo.getMerId());
                    String uzai_wx_group_member = merchantService.getMechantOtherEsIndexName(uzai_workwx_group_member, wxqAddFriendTaskAddInfo.getMerId());
                    Map<String,Object> dataMp_member = elasticsearchUtilGroupMsg.searchDataById(uzai_workwx_group_member, memberId, null);
                    EsWorkWxGroupMember esWorkWxGroupMember  = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(dataMp_member)), EsWorkWxGroupMember.class);
                    if(esWorkWxGroupMember != null){
                        corpid = Tools.getStr(esWorkWxGroupMember.getCorpId());
                    }
                    //发送添加好友MQ消息
                    MsgDto<AddFriendReqWxworkDto> msgDto = new MsgDto<>();
                    AddFriendReqWxworkDto addFriendReqWxworkDto = new AddFriendReqWxworkDto();
                    addFriendReqWxworkDto.setWxid(wxqAddFriendTaskAddInfo.getWxid());
                    addFriendReqWxworkDto.setGroupId(wxqAddFriendTaskAddInfo.getGroupWxid()); //群wxid
                    addFriendReqWxworkDto.setVerify(Tools.getStr(wxqAddFriendTask.getVerifyMsg()));
                    addFriendReqWxworkDto.setCorpid(corpid);
                    msgDto.setContent(addFriendReqWxworkDto);
                    msgDto.setId(IdWorker.getId());
                    msgDto.setDeviceType(device.getRecvmsgType());
                    msgDto.setDeviceUniqueId(device.getId());
                    msgDto.setMerId(wxqAddFriendTaskAddInfo.getMerId());
                    msgDto.setMsgType(MessageFuncEnum.ADD_GROUPMEMBER_TO_FRIENDS.getValue());
                    UzaiRespVo<Object> uzaiRespVo = uzaiImClientFeignService.wxworkAddGroupmemberTofriends(msgDto);
                    logger.info("企业微信群内添加好友发送消息：para={},result={}",JSONObject.toJSONString(msgDto),JSONObject.toJSONString(uzaiRespVo));
                }
            }

            //删除添加好友发送明细记录
            wxqAddFriendTaskAddInfoMapper.deleteById(wxqAddFriendTaskAddInfo.getId(), wxqAddFriendTaskAddInfo.getMerId());

            //修改当日数，当日数+1
            wxqAddFriendTask.setAddDayNum(wxqAddFriendTask.getAddDayNum() + 1);
            //修改发送总数，当前发送总数+1
            wxqAddFriendTask.setAddNum(wxqAddFriendTask.getAddNum() + 1);

            wxqAddFriendTaskMapper.updateById(wxqAddFriendTask);


        }else{//添加完成，则需要修改任务为已完成
            wxqAddFriendTask.setStatus(WxqAddFriendTaskStatusEnum.COMPLETED.getId());
            wxqAddFriendTaskMapper.updateById(wxqAddFriendTask);
        }
    }

}
